package com.codedef.cidaren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codedef.cidaren.common.exception.CustomException;
import com.codedef.cidaren.common.response.Result;
import com.codedef.cidaren.common.response.ResultCode;
import com.codedef.cidaren.constants.JwtConstant;
import com.codedef.cidaren.dao.CdkeyDao;
import com.codedef.cidaren.dao.UserDao;
import com.codedef.cidaren.entity.CdkeyEntity;
import com.codedef.cidaren.service.CdkeyService;
import com.codedef.cidaren.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class CdkeyServiceImpl implements CdkeyService {

    @Autowired
    CdkeyDao cdkeyDao;

    @Autowired
    UserDao userDao;

    /**
     * Cdkey的兑换
     * @param token
     * @param cdkey
     * @return
     */
    public Map<String, Object> conversionCdkey(String token, String cdkey, String userIp) {
        // 获得用户的id
        token = token.split(" ")[1];
        Claims cla = JwtUtils.parseToken(token, "dG9tbXlhbmRnaW5h");
        Integer userId = (int) cla.get("id");
        String username = (String) cla.get("username");
        // 验证CDKEY
        CdkeyEntity cdkeyEntity = cdkeyDao.selectOne(new QueryWrapper<CdkeyEntity>().eq("cdkey", cdkey));
        if (cdkeyEntity == null) {
            // Cdkey不存在
            throw new CustomException(ResultCode.CDKEY_NON_EXISTENT);
        }
        if (cdkeyEntity.getStatus() != 0) {
            // Cdkey不存在
            throw new CustomException(ResultCode.CDKEY_HAVE_BEEN_USED);
        }

        // 执行兑换
        doConversion(userId, cdkey, userIp);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("name", cdkeyEntity.getName());
        resultMap.put("num", cdkeyEntity.getNum());
        return resultMap;
    }

    @Transactional
    int doConversion(Integer userId, String cdkey, String userIp) {
        // 查出cdkeyEntity
        CdkeyEntity cdkeyEntity = cdkeyDao.selectOne(new QueryWrapper<CdkeyEntity>().eq("cdkey", cdkey));
        // 为用户充值
        userDao.addTax(userId, cdkeyEntity.getNum());
        // 更改CDKEY
        cdkeyEntity.setUseTime(new Date());
        cdkeyEntity.setStatus(1);
        cdkeyEntity.setUserIp(userIp);
        cdkeyEntity.setUserId(userId);
        cdkeyDao.updateById(cdkeyEntity);

        return 1;
    }

}
